package com.trade.common.utils.transform;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.CompactWriter;
import com.thoughtworks.xstream.io.xml.DomDriver;

import java.io.StringWriter;
import java.io.Writer;
import java.util.Iterator;
import java.util.Map;

/**
 * XML工具类
 */
public class XmlUtil {
    /**
     * XML转对象
     * @param xmlStr 要转换的XML字符串
     * @param cls 要转换成的对象类
     * @return 转换后的对象
     */
    public static <T> T xmlToObj(String xmlStr, Class<T> cls) {
        try {
            XStream xstream = new XStream(new DomDriver());
            xstream.processAnnotations(cls); //使用注解的方式
            @SuppressWarnings("unchecked")
            T t = (T) xstream.fromXML(xmlStr);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 描述：对象转XML（XStream方式）
     * @param obj
     * @format 是否格式化
     * @return
     */
    public static String objToXmlByXStream(Object obj, boolean format) {
        XStream xStream = new XStream();
        xStream.processAnnotations(obj.getClass()); //通过注解方式的
        if (format) {
            //格式化输出
            //			return xStream.toXML(entity).replaceAll("__","_");
            return xStream.toXML(obj);
        } else {
            //无格式输出
            Writer writer = new StringWriter();
            xStream.marshal(obj, new CompactWriter(writer));
            //	        return writer.toString().replaceAll("__","_");
            return writer.toString();
        }
    }

    /**
     * 描述：对象转XML（无格式输出）
     * @param obj 要转换的对象
     * @return 转换后的XML串
     */
    public static String objToXml(Object obj) {
        return XmlUtil.objToXml(obj, false);
    }

    /**
     * 描述：对象转XML
     * @param obj
     * @format 是否格式化
     * @return
     */
    public static String objToXml(Object obj, boolean format) {
        if (obj instanceof Map) {
            return XmlUtil.mapToXml((Map) obj);
        } else {
            return XmlUtil.objToXmlByXStream(obj, format);
        }
    }

    /**
     * 描述：将Map格式数据转换成XML格式数据
     * @param params 参数Map格式
     * @return XML格式
     */
    public static String mapToXml(Map<String, String> params) {
        String param = "";
        if (params != null) {
            Iterator<String> it = params.keySet().iterator();
            while (it.hasNext()) {
                String str = it.next();
                param += "<" + str + ">";
                param += params.get(str);
                param += "</" + str + ">";
            }
        }
        return param;
    }

    /**
     * 描述：获取XML标签（包括内容）
     * @param xml 目标XML
     * @param tagName 标签名称
     * @return 截取后的xml子串
     */
    public static String getXmlTag(String xml, String tagName) {
        String str = "";
        try {
            if (tagName == null) {
                return "";
            }
            if (xml != null && xml.length() > 0) {
                int begin = xml.indexOf(tagName);
                int end = xml.indexOf("</" + tagName + ">");
                end = xml.indexOf(">", end);
                if (end > begin) {
                    str = xml.substring(begin - 1, end + 1);
                    str = str.replaceAll("<", "<");
                    str = str.replaceAll(">", ">");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 描述：获取XML标签内容（不包括本标签）
     * @param xml 目标XML
     * @param tagName 标签名称
     * @return 截取后的xml子串
     */
    public static String getXmlTagContent(String xml, String tagName) {
        String str = "";
        try {
            if (tagName == null) {
                return "";
            }
            if (xml != null && xml.length() > 0) {
                int begin = xml.indexOf(tagName);
                begin = xml.indexOf(">", begin);
                int end = xml.indexOf("</" + tagName + ">");
                if (end > begin) {
                    str = xml.substring(begin + 1, end);
                    str = str.replaceAll("<", "<");
                    str = str.replaceAll(">", ">");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    public static void main(String[] args) {
        String xml =
            "<TcpCont>\n" + "  <ActionCode>1</ActionCode>\n" +
            "  <TransactionID>6003110001201603240000000001</TransactionID>\n" +
            "  <RspTime>20160324105146</RspTime>\n" + "  <RspCode>0000</RspCode>\n" + "  <RspDesc>查询成功</RspDesc>\n" +
            "</TcpCont>";
        String tag = XmlUtil.getXmlTag(xml, "ActionCode");
        System.out.println(tag);
        String tagContent = XmlUtil.getXmlTagContent(xml, "ActionCode");
        System.out.println(tagContent);
    }

}
